<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Auth extends MX_Controller {

	function __construct()
	{
		parent::__construct();
		$this->load->library('ion_auth');
		$this->load->library('form_validation');
		$this->load->helper('url');

		// Load MongoDB library instead of native db driver if required
		//$this->config->item('use_mongodb', 'ion_auth') ?
		//$this->load->library('mongo_db') :

		$this->load->database();

		$this->form_validation->set_error_delimiters($this->config->item('error_start_delimiter', 'ion_auth'), $this->config->item('error_end_delimiter', 'ion_auth'));

		//$this->lang->load('auth');
		//$this->load->helper('language');
	}


	//log the user in
	function login()
	{
		
		//validate form input
		$this->form_validation->set_rules('login-usuario', 'Identity', 'required');
		$this->form_validation->set_rules('login-passwd', 'Password', 'required');
		
		
		if (!$this->ion_auth->logged_in()){
			
			if ($this->form_validation->run() == true)
			{
				//check to see if the user is logging in
				//check for "remember me"
				//$remember = (bool) $this->input->post('remember');
	
				$remember=true;
				
				if ($this->ion_auth->login($this->input->post('login-usuario'), $this->input->post('login-passwd'), $remember))
				{
					//if the login is successful
					//redirect them back to the home page
					$this->session->set_flashdata('message', $this->ion_auth->messages());
					redirect($this->input->post('current_url'), 'refresh');
				}
				else
				{
					//if the login was un-successful
					//redirect them back to the login page
					$this->session->set_flashdata('message', $this->ion_auth->errors());
					redirect($this->input->post('current_url'), 'refresh'); //use redirects instead of loading views for compatibility with MY_Controller libraries
				}
			}
			else
			{
				//the user is not logging in so display the login page
				//set the flash data error message if there is one
				//$data['current_url']=$this->input->post('current_url');
				
				//$this->load->view('login', $data);
				$this->session->set_flashdata('message', 'No has rellenado los datos');
				redirect($this->input->post('current_url'), 'refresh');
			}
		}
	}

	//log the user out
	function logout()
	{
		//log the user out
		$logout = $this->ion_auth->logout();

		//redirect them to the login page
		$this->session->set_flashdata('message', $this->ion_auth->messages());
		redirect('', 'refresh');
	}
}
